import store from '../store'
import Tools from '../utils/tools'

export const websocket = initWS();

// 初始化websocket
export function initWS(){
  if ('WebSocket' in window) {
    if(store.getters.userId && (!websocket
      || typeof websocket == 'undefined'
      || (websocket.readyState !== websocket.OPEN
      && websocket.readyState !== websocket.CONNECTING))){
      // let _ws = new WebSocket("ws://localhost:8888/messages?userid="+store.getters.userId)
      let _uri = Tools.isDev()?'localhost:8888':Tools.getBaseURI();
      let _ws = new WebSocket("ws://"+_uri+"/messages?userid="+store.getters.userId)
      //数据接收
      _ws.onmessage = websocketonmessage

      return _ws
    }
  }
  else {
    this.$message.error('对不起，您的浏览器不支持消息推送！')
  }
  return null
}

// websocket主动请求服务端
export function sentToServer(msg) {
  // 实际调用的方法 如果ws已经连接则直接发送消息；如正在开启状态，则等待300毫秒，再发送消息；若未开启 ，则等待500毫秒，再发送消息。
  //若是ws开启状态
  if(websocket){
    if (websocket.readyState === websocket.OPEN) {
      websocketsend(msg)
    }
    // 若是 正在开启状态，则等待300毫秒
    else if (websocket.readyState === websocket.CONNECTING) {
      setTimeout(function () {
        websocketsend(msg)
      }, 300);
    }
  }
  // 若未开启 ，则等待500毫秒
  else {
    initWS();
    setTimeout(function () {
      websocketsend(msg)
    }, 500);
  }
}

// 关闭websocket
export function closeWS(){
  if(websocket)
    websocket.close()
}

function websocketonmessage(e){ //数据接收
  // console.log('接收到新消息：',JSON.parse(e.data));
  store.dispatch('pushNewMsg', JSON.parse(e.data));
}

function websocketsend(agentData){//数据发送
  if(websocket)
    websocket.send(agentData);
}
